<?php

namespace App\Listeners\OpenShop;

use App\Enums\OpenShop\InvestmentPromotion\OpenShopCacheEnum;
use App\Events\OpenShop\OrderCreatedEvent;
use App\Library\FeiShu\SendFs;
use App\Library\Rms\RmsUserApi;
use App\Listeners\BaseListener;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class CreateMerchantUser extends BaseListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Handle the event.
     *
     * @param OrderCreatedEvent $event
     * @return void
     */
    public function handle(OrderCreatedEvent $event)
    {
        $orderNo = $event->order->orderNo;

        Log::channel('listener')
           ->info(__CLASS__ . " handle CreateMerchantUser...orderNo: {$orderNo} in...");

        $mobile  = (string)optional($event->order->baseInfoRel)->mobile;
        $name    = (string)optional($event->order->identityCardRel)->name;

        // 参数错误
        if (!$mobile || !$name) {
            Log::channel('listener')
               ->info(__CLASS__ . " handle CreateMerchantUser...orderNo: {$orderNo} data error",
                   [$mobile, $name]);

            $content = [
                'name'    => $name,
                'mobile'  => $mobile,
                'orderNo' => $orderNo,
            ];

            SendFs::newRobot()->setTitleContent('创建商家账号参数错误', json_encode($content))->send();
            return;
        }

        // curl
        $curlName = $name . ((string)optional($event->order->identityCardRel)->id);
        $userApi  = (new RmsUserApi())->createUser($mobile, $curlName);
        $userId   = $userApi['data']['userId'] ?? -1;
        $password = $userApi['data']['password'] ?? '';

        // 接口调用失败
        if (!isset($userApi['code']) || $userApi['code'] != 1) {
            Log::channel('listener')
               ->info(__CLASS__ . " handle CreateMerchantUser...orderNo: {$orderNo} api error", $userApi);

            $content = [
                'name'    => $name,
                'mobile'  => $mobile,
                'orderNo' => $orderNo,
                'errmsg'  => $userApi['msg'] ?? '',
            ];

            SendFs::newRobot()->setTitleContent('创建商家账号失败', json_encode($content))->send();
            return;
        }

        // 更新加盟商id字段
        OpenShopSignOrderModel::saveMerchantUserId($orderNo, $userId);

        // 设置初始密码Cache
        if ($password) {
            Cache::put(OpenShopCacheEnum::getShopManagerPwd($mobile), $password, 86400*7);
        }

        // success
        Log::channel('listener')
           ->info(__CLASS__ . " handle CreateMerchantUser...orderNo: {$orderNo} success");
    }
}
